package com.epfresh.supplier.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.entity.TagPager;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseFragment;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.OrderSurePrepareDialog;
import com.epfresh.api.widget.list.LoadMoreListView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.supplier.R;
import com.epfresh.supplier.activity.H5OrderDetailActivity;
import com.epfresh.supplier.activity.OrderEnsureActivity;
import com.epfresh.supplier.activity.OrderLogisticsInfoActivity;
import com.epfresh.supplier.adapter.OrderAdapter;
import com.epfresh.supplier.adapter.OrderJoinAdapter;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.OrderJoinListBean;
import com.epfresh.supplier.entity.OrderListBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zzq on 2017/9/14.
 */
public class OrderFragment extends BaseFragment implements LoadMoreListView.IXListViewListener, OrderSurePrepareDialog.IDialogSure {
    //待支付 2待发货 3 待收货 4 拒签（不显示） 5退款 6 交易取消 7 交易成功 9 待评价 10减免退
    boolean typeFlag;//订单类别展示开关
    //订单列表类别 1,待支付 2,未完成,3已完成 4全部订单
    public int typeState;
    //0线上,1线下,2现场，当前暂时默认现场等同线下
    public int typeOnline;

    private LoadMoreListView lvContent;

    private List<OrderListBean> list = new ArrayList<>();
    private List<OrderJoinListBean> joinlist = new ArrayList<>();

    protected View mainView;
    protected View vException;
    protected TextView tvExceptionDescription;
    protected ImageView ivExceptionIcon;
    private ProgressBar pb;
    public int requestSucceedCount = 0;
    private int PAGE_SIZE = 5;
    OrderAdapter adapter;
    OrderJoinAdapter joinadpt;
    Context context;
    BaseActivity baseActivity;
    int postionFlag;
    TagPager tagPager = new TagPager();

    @Override
    public String getBaseTag() {
        return Constant.TAG_ORDER_FRAGMENT;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            typeOnline = savedInstanceState.getInt("type", 10);
        }
        return inflater.inflate(R.layout.fragment_order,
                container, false);
    }

    @Override
    public void onViewCreated(View v, Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);
        context = getContext();
        baseActivity = getAppActivity();
        initHeadView(v);
        lvContent = (LoadMoreListView) v.findViewById(R.id.lv_content);

        vException = v.findViewById(R.id.v_exception);
        mainView = v.findViewById(R.id.fragment_ptr_home_ptr_frame);
        initException();
        if (typeOnline != 30) {
            adapter = new OrderAdapter(context, lvContent, list, typeOnline);
            adapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View v, int position, long l) {
                    Log.e("new onItemClick", "" + position);

// 交货码，查看物流，取消订单，确认收货，支付， 详情
                    switch (v.getId()) {
                        case R.id.tv_phone:
                            Intent call = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + list.get(position).getReceiverPhone()));//调出来拨打页面；
                            context.startActivity(call);
                            break;
                        case R.id.tv_post_type://
                        case R.id.tv_logistics:
                            Intent logisticsInfo = new Intent(context, OrderLogisticsInfoActivity.class);
                            logisticsInfo.putExtra("logisticsNo", list.get(position).getOrderId());
                            context.startActivity(logisticsInfo);
                            break;
                        case R.id.ll_order:
                        case R.id.rl_more:
                        case R.id.ll_images:
                            Intent detail = new Intent(context, H5OrderDetailActivity.class);
                            detail.putExtra("orderId", list.get(position).getOrderId());
                            detail.putExtra(com.epfresh.api.constant.Constant.KEY_WEB_URL, "http://m.epfresh.com/help/order_supply_new.html?orderId=" + list.get(position).getOrderId());
                            detail.putExtra(com.epfresh.api.constant.Constant.KEY_WEB_TITLE, "订单详情");
                            startActivityForResult(detail, 0x002);
                            break;

                        case R.id.tv_code:
                            Intent code = new Intent(context, OrderEnsureActivity.class);
                            code.putExtra("id", list.get(position).getOrderId());
                            //code.putExtra("listFlag", true);
                            Log.e("result", "___");
                            Log.e("result", "shuaxin");

                            startActivityForResult(code, 0x002);

                            break;
                        case R.id.tv_sure:
                            postionFlag = position;
                            int deliveryType = list.get(position).getDeliveryType();
                            if (deliveryType == 4) {
                                OrderSurePrepareDialog prepare = new OrderSurePrepareDialog(context, OrderFragment.this, list.get(postionFlag));
                                prepare.show();
                            } else {
                                orderSure("");
                            }

                            break;
                    }
                }
            });
            lvContent.setAdapter(adapter);
        } else {
            joinadpt = new OrderJoinAdapter(context, lvContent, joinlist, typeOnline);
            joinadpt.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View v, int position, long l) {
                    Log.e("new onItemClick", "" + position);

// 交货码，查看物流，取消订单，确认收货，支付， 详情


                    Intent detail = new Intent(context, H5OrderDetailActivity.class);
                    detail.putExtra("orderId", joinlist.get(position).getId() + "");
                    detail.putExtra(com.epfresh.api.constant.Constant.KEY_WEB_URL, "http://mtest.epfresh.com/cntest/supply/order_supply_joint.html?goodId=" + joinlist.get(position).getId());
                    detail.putExtra(com.epfresh.api.constant.Constant.KEY_WEB_TITLE, "订单详情");
                    startActivityForResult(detail, 0x002);
                }
            });
            lvContent.setAdapter(joinadpt);
        }
        lvContent.setXListViewListener(this);
        refresh();
    }


    public void initException() {
        tvExceptionDescription = (TextView) vException.findViewById(R.id.tv_exception);
        ivExceptionIcon = (ImageView) vException.findViewById(R.id.iv_exception);
        pb = (ProgressBar) vException.findViewById(R.id.pb);
    }

    private PtrFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, lvContent, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    boolean refreshFlag = false;

    public void refresh() {
        if (lvContent == null)
            return;
        lvContent.resetNoMore();
        requestSucceedCount = 0;
        refreshFlag = true;
        loadData(0);
    }

    @Override
    public void onLoadMore() {
        int number = tagPager.getNumber();
        //loadData(type, number + 1);
        loadData(number + 1);
    }

    public void updateViewStatus(RequestTag requestTag) {
        ptrFrameLayout.refreshComplete();
        if (tagPager.isLast()) {
            lvContent.noMore();
        } else {
            lvContent.stopLoadMore();
        }
    }


    private void initHeadView(View v) {
        ptrFrameLayout = (PtrFrameLayout) v.findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt("typeState", typeState);
        outState.putInt("typeOnline", typeOnline);
        super.onSaveInstanceState(outState);
    }


    void loadData(int page) {
        if (typeOnline != 30) {
            RequestEntitySupply<Map<String, String>> entity = new RequestEntitySupply<>();
            Map<String, String> map = new HashMap<>();
            map.put("storeId", BaseApplication.getInstance().getStoreId());

            map.put("pageNumber", page + "");
            map.put("pageSize", PAGE_SIZE + "");
            map.put("type", "" + typeState);
            map.put("storeId", BaseApplication.getInstance().getStoreId());
            map.put("parentSource", "" + typeOnline);
            //map.put("sortProperty", "placeOrderTime");
            //map.put("sortDirection", "DESC");
            //entity.setCmd("appOrder/supplyOrdersListS2"); supplier/order/list
            entity.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_order_supplier_order_list);
            entity.setParameters(map);
            RequestTag requestTag = new RequestTag();
            requestTag.tag = com.epfresh.api.constant.AppSupplyRouterConstant.cmd_order_supplier_order_list;
            requestTag.action = page;

            requestTag.type = RequestTag.TYPE_CURRENT;
            request(entity, requestTag, onRequestListener);
        } else {
            RequestEntitySupply<Map<String, String>> entity = new RequestEntitySupply<>();
            Map<String, String> map = new HashMap<>();
            map.put("pageNumber", page + "");
            map.put("pageSize", PAGE_SIZE + "");
            map.put("type", "" + typeState);
            entity.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_order_supplier_order_joinList);
            entity.setParameters(map);
            RequestTag requestTag = new RequestTag();
            requestTag.tag = com.epfresh.api.constant.AppSupplyRouterConstant.cmd_order_supplier_order_joinList;
            requestTag.action = page;
            requestTag.type = RequestTag.TYPE_CURRENT;
            request(entity, requestTag, onRequestjoinListener);
        }

    }

    /**
     * 联营订单分开接口监听
     */

    OnRequestListener<ContentEntity<OrderJoinListBean>> onRequestjoinListener = new OnRequestListener<ContentEntity<OrderJoinListBean>>() {
        @Override
        public ContentEntity<OrderJoinListBean> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<ContentEntity<OrderJoinListBean>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
            if (requestSucceedCount == 0) {
                showExceptionView(R.mipmap.order_no, "网络问题,请点击重试", HttpRequest.FAIL_NET_FAULT);
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (requestSucceedCount == 0) {
                showExceptionView(R.mipmap.order_no, arg + "", HttpRequest.FAIL_NET_FAULT);//arg + ",请点击重试"
            }
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
        }

        @Override
        public void onStart(Object tag) {
            if (requestSucceedCount == 0 && !refreshFlag) {
                showProgressView();
            } else
                refreshFlag = false;
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<OrderJoinListBean>> response, Object tag) {
            //页面第一次调用网络请求接口并成功
            showMainView();
            RequestTag requestTag = (RequestTag) tag;
            if (requestTag.action == 0 || requestSucceedCount == 0) {
                joinlist.clear();
            }
            requestSucceedCount++;

            ContentEntity<OrderJoinListBean> orderResponse = response.getResponseElement();
            List<OrderJoinListBean> content = orderResponse.getContent();
            tagPager.setLast(orderResponse.getLast());
            tagPager.setNumber(orderResponse.getNumber());
            tagPager.setSize(orderResponse.getSize());
            tagPager.setTotalElements(orderResponse.getTotalElements());
            joinlist.addAll(content);
            joinadpt.notifyDataSetChanged();
            if (orderResponse.getNumber() == 0) {
                lvContent.setSelection(0);
            }
            updateViewStatus(requestTag);
            if (joinlist.size() == 0) {
                showExceptionView(R.mipmap.order_no, "暂无订单", HttpRequest.FAIL_DATA_EMPTY);
            }
        }
    };


    OnRequestListener<ContentEntity<OrderListBean>> onRequestListener = new OnRequestListener<ContentEntity<OrderListBean>>() {
        @Override
        public ContentEntity<OrderListBean> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<ContentEntity<OrderListBean>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
            if (requestSucceedCount == 0) {
                showExceptionView(R.mipmap.order_no, "网络问题,请点击重试", HttpRequest.FAIL_NET_FAULT);
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (requestSucceedCount == 0) {
                showExceptionView(R.mipmap.order_no, arg + "", HttpRequest.FAIL_NET_FAULT);//arg + ",请点击重试"
            }
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
        }

        @Override
        public void onStart(Object tag) {
            if (requestSucceedCount == 0 && !refreshFlag) {
                showProgressView();
            } else
                refreshFlag = false;
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<OrderListBean>> response, Object tag) {
            //页面第一次调用网络请求接口并成功
            showMainView();
            RequestTag requestTag = (RequestTag) tag;
            if (requestTag.action == 0 || requestSucceedCount == 0) {
                list.clear();
            }
            requestSucceedCount++;

            ContentEntity<OrderListBean> orderResponse = response.getResponseElement();
            List<OrderListBean> content = orderResponse.getContent();
            tagPager.setLast(orderResponse.getLast());
            tagPager.setNumber(orderResponse.getNumber());
            tagPager.setSize(orderResponse.getSize());
            tagPager.setTotalElements(orderResponse.getTotalElements());
            list.addAll(content);
            adapter.notifyDataSetChanged();
            if (orderResponse.getNumber() == 0) {
                lvContent.setSelection(0);
            }
            updateViewStatus(requestTag);
            if (list.size() == 0) {
                showExceptionView(R.mipmap.order_no, "暂无订单", HttpRequest.FAIL_DATA_EMPTY);
            }
        }
    };


    public void showMainView() {
        vException.setVisibility(View.GONE);
        mainView.setVisibility(View.VISIBLE);
    }


    public void showExceptionView(int imgSrc, String text, int exceptionType) {
        if (imgSrc > 0) {

        }
        pb.setVisibility(View.GONE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.VISIBLE);
        ivExceptionIcon.setVisibility(View.VISIBLE);
        mainView.setVisibility(View.GONE);

        ivExceptionIcon.setImageResource(imgSrc);
        tvExceptionDescription.setText(text);
        tvExceptionDescription.setTag(exceptionType);
        ivExceptionIcon.setTag(exceptionType);
        tvExceptionDescription.setOnClickListener(this);
        ivExceptionIcon.setOnClickListener(this);
    }

    public void showProgressView() {

        pb.setVisibility(View.VISIBLE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.GONE);
        ivExceptionIcon.setVisibility(View.GONE);
        mainView.setVisibility(View.GONE);
    }


    /**
     * 备货完成
     */
    @Override
    public void orderSure(String date) {
        RequestEntitySupply<Map<String, Object>> data = new RequestEntitySupply<>();
        data.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_order_supplier_order_endPickup);//原接口见如下
        Map<String, Object> map = new HashMap<>();
        map.put("storeId", BaseApplication.getInstance().getStoreId());
        if (!TextUtils.isEmpty(date)) map.put("estimateTime", date);
        map.put("orderId", list.get(postionFlag).getOrderId());
        data.setParameters(map);
        Log.e("post_sure:", data.toString());
        ((BaseActivity) context).request(data, "appOrder/supplyAppSendGoodsPickUpS2", onPostRequestListener);
    }

    OnRequestListener<StatusEntity> onPostRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
            StatusEntity responseElement = response.getResponseElement();

            if (responseElement.isSuccess()) {
/*                if(type==0) {
                    list.get(postionFlag).setButtonTypex(92);
                }else{
                    list.remove(postionFlag);
                }
                adapter.notifyDataSetChanged();*/
                refresh();
                T.toast(BaseApplication.getDoc().getPrepareSure());
            } else {
            }
        }
    };


}
